package handler

import (
	"api/commont"
	"api/config"
	"api/internal/request"
	"api/pkg"
	pb "driver_certification_srv/proto"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"time"
)

func DriverRegister(c *gin.Context) {
	json := request.DriverRegisterRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		commont.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	client, err := grpc.Dial("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		commont.JsonRes(c, 400, err.Error(), nil)
		return
	}
	con := pb.NewDriverClient(client)
	req := &pb.DriverRegisterReq{
		Username: json.Username,
		Password: json.Password,
	}
	register, err := con.DriverRegister(c, req)
	if err != nil {
		commont.JsonRes(c, 400, err.Error(), nil)
		return
	}
	claims := pkg.CustomClaims{
		ID:             uint(register.Id),
		StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().Unix() + int64(config.DataConfig.Jwt.Seconds)},
	}
	newJWT := pkg.NewJWT(config.DataConfig.Jwt.Key)
	token, err := newJWT.CreateToken(claims)
	if err != nil {
		commont.JsonRes(c, 400, err.Error(), nil)
		return
	}
	commont.JsonRes(c, 200, "注册成功", token)
}
